package com.xuecheng.content.service.impl;

import com.xuecheng.content.config.MinioProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.util.Map;

@Component
@Slf4j
public class PublishHtmlService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private MinioProperties properties;

    @Async(value="taskExecutor")
    public void publish(Map<String,Object> map, Long coursePubId) throws Exception {
        log.info("生成静态页线程："+Thread.currentThread().getName());
        //睡眠20秒，表示网络慢
        //Thread.sleep(20000);
        //5、页面静态化（获取html字符串）
        Template template = configuration.getTemplate("learing_article.ftl");
        //5.4 根据数据和模板，调用工具，获取静态页面的字符串
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
        //5.5 构建输入流
        ByteArrayInputStream stream = new ByteArrayInputStream(html.getBytes());

        //6、存入MinIo中
        //6.1 准备文件的名称
        String path = "/pages/" + coursePubId + ".html";  //html文件名称 = 课程发布id.html
        //6.2 构造PutObjectArgs
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .contentType("text/html")
                .stream(stream, stream.available(), -1)  //输入流
                .bucket(properties.getBucket())
                .object(path)
                .build();
        //6.3 调用minioClient方法进行上传
        minioClient.putObject(putObjectArgs);
    }
}
